﻿/*
 * Created by SharpDevelop.
 * User: Администратор
 * Date: 28.03.2011
 * Time: 11:22
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.IO;
using Video;

namespace Video.FLV
{
	/// <summary>
	/// Description of Decoder.
	/// </summary>
	public class Decoder:IDisposable
	{
		Logger log;
		VideoStream videoStream;
		
		public Decoder(string inFilePath)
		{
			videoStream = new VideoStream(inFilePath);
			log =  LogManager.GetCurrentClassLogger();
		}
		
		public byte GetHighTetra(byte source){
			byte distination = (byte)(source >> 4);
			return distination;
		}
		
		public byte GetLowTetra(byte source){
			byte distination = (byte)(source & 15);
			return distination;
		}
		
		public FLVHeader GetHeader(){
			FLVHeader temp = new FLVHeader();
			//temp.Signature1 = videoStream .ReadByte();
			temp.Signature2 = stream.ReadByte();
			temp.Signature3 = stream.ReadByte();
			temp.Version = stream.ReadByte();
			temp.TypeFlags = stream.ReadByte();
			//temp.TypeFlagsAudio = stream.ReadByte();
			//temp.TypeFlagsReserved1 = stream.ReadByte();
			//temp.TypeFlagsVideo = stream.ReadByte();
			temp.DataOffset = ReadInt32BigEdian();
			return temp;
		}
		
		public FLVBody GetBody(){
			FLVBody temp = new FLVBody();
			temp.FlvTag = GetTag();
			if(temp.FlvTag.TagType==9){
				//пока здесь считаем
				byte[] buf = new byte[temp.FlvTag.DataSize-1];
				buf = stream.ReadBytes((int)temp.FlvTag.DataSize-1);
				newstream.Write(buf);
			}
			else{
				stream.BaseStream.Seek((long)temp.FlvTag.DataSize-1, SeekOrigin.Current);
			}
			
			temp.PreviousTagSize = ReadInt32BigEdian();
			return temp;
		}
		
		public FLVTag GetTag(){
			FLVTag temp = new FLVTag();
			temp.TagType = stream.ReadByte();
			temp.DataSize = ReadInt24();
			temp.Timestamp = ReadInt24();
			temp.TimestampExtended = stream.ReadByte();
			temp.StreamID = ReadInt24();
			temp.VideoData = GetVideo();
			return temp;
		}
		
		public FLVVideoData GetVideo(){
			FLVVideoData temp = new FLVVideoData();
			byte tempbyte = stream.ReadByte();
			temp.FrameType = GetHighTetra(tempbyte);
			temp.CodecID = GetLowTetra(tempbyte);
			return temp;
		}
		
		public void GoToNextTag(FLVTag tag){
			stream.BaseStream.Seek((long)tag.DataSize, SeekOrigin.Current);
		}
		
		public bool isEnd(){
			if(stream.PeekChar()==-1){
				return true;
			}
			return false;
		}
		
		public void Dispose()
		{
		}
	}
}
